package com.javaweb.service.impl;

import com.javaweb.common.BusinessConstants;
import com.javaweb.dao.ArticleDao;
import com.javaweb.dao.UserDao;
import com.javaweb.model.Article;
import com.javaweb.model.User;
import com.javaweb.service.ArticleService;
import com.javaweb.service.dto.ArticleConditionDto;
import com.javaweb.service.dto.ArticleUpdateDto;
import com.javaweb.service.dto.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @desc:
 * @author: hjm
 * @date: 2024/10/16 9:47
 */

@Service
@Slf4j
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private UserDao userDao ;
    @Autowired
    private ArticleDao articleDao ;


    @Override
    public PageResult queryByArticleCondition(ArticleConditionDto articleCond, Integer pageNum, Integer pageSize) {
        // 计算开始的记录数
        int start = (pageNum - 1) * pageSize;

        // 查询总记录数
        int totalItems = articleDao.selectCountByCondition(articleCond);

        // 查询当前页的文章列表
        List<Article> articles =articleDao.selectByArticleCondition(articleCond);

        // 计算总页数
        int totalPages = (int) Math.ceil((double) totalItems / pageSize);

        PageResult<Article> pageResult = new PageResult<>();
        pageResult.setData(articles);
        pageResult.setPageNum(pageNum);
        pageResult.setPageSize(pageSize);
        pageResult.setTotal(totalItems);

        return pageResult;
    }

    @Override
    public Article queryById(String articleId) {
        return articleDao.selectById(Integer.valueOf(articleId));
    }

    @Override
    public Article insertArticle(Article article) {
        articleDao.insert(article);
        return article;
    }

    @Transactional
            (
            propagation = Propagation.REQUIRED,
            isolation = Isolation.DEFAULT,
            timeout = -1,
            readOnly = false,
            rollbackFor = Throwable.class
    )
    @Override
    public int publishArticle(String articleId, String userId) {

        Integer ret =  articleDao.updateStatus(Integer.valueOf(articleId),
                               BusinessConstants.ARTICLE_PUBLISHED) ;
        if (ret > 0) {
            ret = userDao.updateScore(Integer.valueOf(userId),
                    BusinessConstants.ARTICLE_SCORE) ;
        } else {
            log.error("publish article : update status failed." ) ;
            return 0 ;
        }
        try {
            if (true) {
                throw new RuntimeException("exception.");
            }
        } catch (Exception e) {
            log.error(e.getMessage()) ;
        }
        log.info("publish article successfully." ) ;
        return ret;
    }


    @Transactional(
            propagation = Propagation.REQUIRED,
            isolation = Isolation.DEFAULT,
            timeout = -1,
            readOnly = false,
            rollbackFor = Throwable.class
    )
    @Override
    public int publishArticleByBatch(String[] articleIds, String userId) {
        for (String articleId : articleIds) {
            int publishResult = publishArticle(articleId, userId);
            if (publishResult == 0) {
                // 任何一篇文章发布失败，整个批量发布失败
                return 0;
            }
        }
        return 1; // 所有文章都发布成功
    }


    @Transactional(
            propagation = Propagation.REQUIRED,
            isolation = Isolation.DEFAULT,
            timeout = -1,
            readOnly = false,
            rollbackFor = Throwable.class
    )
    @Override
    public int updateArticle(ArticleUpdateDto articleUpdateDto) {
        // 根据传入的 ArticleUpdateDto 中的文章 ID 查询数据库中是否存在对应的旧文章
        Article oldArticle = queryById(articleUpdateDto.getId());
        if (oldArticle == null) {
            // 如果文章不存在，记录错误日志并返回 0，表示更新失败
            log.error("更新文章失败，文章 ID 不存在。");
            return 0;
        }
        // 如果 ArticleUpdateDto 中有新的标题不为 null，则调用 articleDao 的 updateTitle 方法更新文章标题
        if (articleUpdateDto.getTitle()!= null) {
            articleDao.updateTitle(oldArticle.getId(), articleUpdateDto.getTitle());
        }
        // 如果 ArticleUpdateDto 中有新的内容不为 null，则调用 articleDao 的 updateContent 方法更新文章内容
        if (articleUpdateDto.getContent()!= null) {
            articleDao.updateContent(oldArticle.getId(), articleUpdateDto.getContent());
        }
        // 返回 1，表示更新成功
        return 1;
    }

    @Transactional(
            propagation = Propagation.REQUIRED,
            isolation = Isolation.DEFAULT,
            timeout = -1,
            readOnly = false,
            rollbackFor = Throwable.class
    )
    @Override
    public int removeArticle(String articleId, String userId) {
        try {
            // 根据文章 ID 查询文章
            Article article = queryById(articleId);
            // 如果文章不存在，直接返回 0，表示删除失败
            if (article == null) {
                return 0;
            }
            // 调用 articleDao 的 deleteById 方法删除文章
            articleDao.deleteById(Integer.valueOf(articleId));
            // 更新用户对应的活动积分，这里减去了 BusinessConstants.ARTICLE_SCORE 的积分
            userDao.updateScore(Integer.valueOf(userId), -BusinessConstants.ARTICLE_SCORE);
            // 返回 1，表示删除成功
            return 1;
        } catch (Exception e) {
            // 如果出现异常，记录错误日志并返回 0，表示删除失败
            log.error("删除文章失败：{}", e.getMessage());
            return 0;
        }
    }
}
